#include "passwd.hpp"
#include "utils.hpp"
#include <fstream>
#include <iostream>
#include <array>
#include <cstdlib>

#ifdef LINE_LEN
#undef LINE_LEN
#endif

#define LINE_LEN 4096

namespace icecode {

  PasswdFile::PasswdFile(std::string path)
  {
    std::ifstream pwd /* passwd file */ (path);
    
    if(pwd.is_open())
      {
	while(!pwd.eof())
	  {
	    std::array<char, LINE_LEN> line;
	    std::string s;
	    pwd.getline(&line[0], LINE_LEN);
	    s = icecode::utils::trim(&line[0]);
	    if(!s.empty()) {
	      std::vector<std::string> fields = icecode::utils::splitString(line.cbegin(), ":", false);
	      PasswdFile::User user(fields[0]);
	      user.setHash(fields[1]);
	      user.setUID(::strtoul(fields[2].c_str(), 0, 10));
	      user.setGID(::strtoul(fields[3].c_str(), 0, 10));
	      user.setName(fields[4]);
	      user.setHome(fields[5]);
	      user.setShell(fields[6]);
	      users.insert(std::pair<std::string, PasswdFile::User>(fields[0], user));
	    }
	  }
	
	pwd.close();
      }
    else throw std::runtime_error("Unable to open the provided passwd file");
  }
  
}
